from mcp.server import FastMCP
from mcp.types import TextContent
import httpx
import json

app = FastMCP("weather-server")

HOST = "https://restapi.amap.com"
KEY = "xxx"

@app.tool(
        name="query_weather",
        description="查询指定地区的天气情况"
)
async def query_weather(address)->list[TextContent]:
    async with httpx.AsyncClient() as client:
        try:
            # 获取地址所在城市
            resp = await client.get(f"{HOST}/v3/geocode/geo", params={
                "key": KEY,
                "address": address
            })
            if resp.status_code != 200:
                return [TextContent(type="text", text=f"request error: {resp.status_code}{resp.content}")]
            resp_dict = json.loads(resp.text)
            if resp_dict["status"] != "1":
                return [TextContent(type="text", text=f"request error: {resp.status_code}{resp_dict['info']}")]
            city = resp_dict["geocodes"][0]["adcode"]

            # 获取城市天气
            resp = await client.get(f"{HOST}/v3/weather/weatherInfo", params={
                "key": KEY,
                "city": city
            })
            if resp.status_code != 200:
                return [TextContent(type="text", text=f"request error: {resp.status_code}{resp.content}")]
            resp_dict = json.loads(resp.text)
            if resp_dict["status"] != "1":
                return [TextContent(type="text", text=f"request error: {resp.status_code}{resp_dict['info']}")]
            return [TextContent(type="text", text=resp.text)]
        except Exception as e:
            raise e 


if __name__ == "__main__":
    # app.run(transport="stdio")
    app.run(transport="sse")
